//
//  KLSGKindViewController.m
//  KaoLaShiGuangFM
//
//  Created by lanou3g on 15/10/29.
//  Copyright © 2015年 com.lanou3g. All rights reserved.
//

#import "KLSGKindViewController.h"
#import "KLSGKindRecommendViewController.h"
#import "KLSGCategoryTool.h"
#import "KLSGKindChildViewController.h"
#import "KLSGSelectedKindView.h"
#import "KLSGDataFail.h"

@interface KLSGKindViewController ()

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *titleArray;
@property (nonatomic, strong) UIButton *lastBtn;

// 推荐页面
@property (nonatomic, strong) KLSGKindRecommendViewController *recommendVC;
// 其他分类页面
@property (nonatomic, strong) KLSGKindChildViewController *childVC;
// 数据加载失败，用于处理的视图
@property (nonatomic, strong) KLSGDataFail *failView;
@property (nonatomic, strong) KLSGCategoryTool *tool;

@end

@implementation KLSGKindViewController

- (void)loadView
{
    [super loadView];
    self.view.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    self.navigationController.navigationBar.translucent = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    [self subView];
    [self setupData];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.navigationController.navigationBar.translucent = NO;
    self.title = self.titles;
    self.tabBarController.tabBar.hidden = YES;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    self.tabBarController.tabBar.hidden = YES;
}

// 加载数据
- (void)setupData
{
    [self.tool setupDataWithUrl:kCategoryChildUrl(self.Id) block:^(NSDictionary *dic) {
        self.titleArray = [NSMutableArray array];
        NSArray *array = dic[@"list"];
        for (NSDictionary *tempDic in array) {
            [self.titleArray addObject:tempDic[@"tname"]];
        }
        [self.titleArray insertObject:@"推荐" atIndex:0];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self addScrollViewContent];
        });
        
    } failDownloadWithBlock:^{
        
        [self.failView netRequestFailWithBlock:^{
            [self setupData];
            [self.failView hidden];
        }];
        [self.view addSubview:self.failView];
    }];
}

// 懒汉加载
- (KLSGKindRecommendViewController *)recommendVC
{
    if (_recommendVC == nil) {
        _recommendVC = [[KLSGKindRecommendViewController alloc] init];
    }
    return  _recommendVC;
}

- (KLSGKindChildViewController *)childVC
{
    if (_childVC == nil) {
        _childVC = [[KLSGKindChildViewController alloc] init];
    }
    return _childVC;
}

- (KLSGDataFail *)failView
{
    if (!_failView) {
        _failView = [[KLSGDataFail alloc] initWithFrame:[UIScreen mainScreen].bounds];
    }
    return _failView;
}

- (KLSGCategoryTool *)tool
{
    if (!_tool) {
        _tool = [[KLSGCategoryTool alloc] init];
    }
    return _tool;
}

// 页面布局
- (void)subView
{
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth - 80, 50)];
    self.scrollView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.scrollView];
    
    UIButton *moreBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    moreBtn.frame = CGRectMake(CGRectGetMaxX(self.scrollView.frame) + 10, CGRectGetMinY(self.scrollView.frame), kScreenWidth - CGRectGetWidth(self.scrollView.frame) - 10, CGRectGetHeight(self.scrollView.frame));
    moreBtn.backgroundColor = [UIColor whiteColor];
    [moreBtn addTarget:self action:@selector(moreSelectAction:) forControlEvents:UIControlEventTouchUpInside];
    [moreBtn setTitle:@"更多" forState:UIControlStateNormal];
    moreBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    moreBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
    [moreBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    moreBtn.titleEdgeInsets = UIEdgeInsetsMake(5, -10, 5, 30);
    [moreBtn setImage:[UIImage imageNamed:@"unfold"] forState:UIControlStateNormal];
    moreBtn.imageEdgeInsets = UIEdgeInsetsMake(20, 50, 20, 10);
    
    [self.view addSubview:moreBtn];
    
    // 分割线
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.scrollView.frame) + 10, 10, 1, 30)];
    lineView.backgroundColor = [UIColor grayColor];
    lineView.alpha = 0.3;
    [self.view addSubview:lineView];
    
    // 设置leftBarButton
    UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:(UIBarButtonSystemItemReply) target:self action:@selector(leftReturn)];
    self.navigationItem.leftBarButtonItem = left;
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor colorWithRed:234 / 256.0 green:79 / 256.0 blue:56 / 256.0 alpha:1];
}

// leftBarButton 响应事件
- (void)leftReturn
{
    [self.navigationController popViewControllerAnimated:YES];
}

// 为scrollView添加内容
- (void)addScrollViewContent
{
    NSInteger width = 0;
    
    for (int i = 0; i < self.titleArray.count; i++) {
        NSString *title = self.titleArray[i];
        // 计算文本所占长度
        CGSize buttonSize = [title sizeWithAttributes:[NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:14] forKey:NSFontAttributeName]];
        
        UIButton *button = [UIButton buttonWithType:(UIButtonTypeCustom)];
        button.frame = CGRectMake(width + 25, 0, buttonSize.width, 50);
        width += buttonSize.width + 25;
        button.tag = 200 + i;
        [button setTitle:title forState:(UIControlStateNormal)];
        [button setTitleColor:[UIColor grayColor] forState:(UIControlStateNormal)];
        button.alpha = 0.7;
        button.titleLabel.font = [UIFont systemFontOfSize:14];
        [button addTarget:self action:@selector(titleBtnAction:) forControlEvents:(UIControlEventTouchUpInside)];
        [self.scrollView addSubview:button];
        
        if ([title isEqualToString:@"推荐"]) {
            [button setTitleColor:[UIColor redColor] forState:(UIControlStateNormal)];
            button.userInteractionEnabled = NO;
            self.lastBtn = button;
            button.alpha = 1;
        }
    }
    // 设置scrollView的滑动距离
    self.scrollView.contentSize = CGSizeMake(width + 20, 30);
    self.scrollView.showsHorizontalScrollIndicator = NO;
    
    [self addChildVC];
}

// 在self.view上添加子视图控制器的视图
- (void)addChildVC
{
    self.recommendVC = [[KLSGKindRecommendViewController alloc] init];
    [self addChildViewController:self.recommendVC];
    self.recommendVC.tname = @"推荐";
    self.recommendVC.Id = self.Id;
    CGRect frame = self.recommendVC.view.frame;
    frame.origin.y = CGRectGetMaxY(self.scrollView.frame);
    self.recommendVC.view.frame = frame;
    [self.view addSubview:self.recommendVC.view];
}

#pragma mark -更多分类按钮
- (void)moreSelectAction:(UIButton *)sender
{
    __block KLSGKindViewController *mySelf = self;
    if (self.titleArray) {
        [KLSGSelectedKindView addPellCollectionViewWithWindowFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) selectData:self.titleArray action:^(CGFloat row) {
            UIButton *button = (UIButton *)[mySelf.scrollView viewWithTag:200 + row];
            [mySelf titleBtnAction:button];
        }];
    }
}

- (void)titleBtnAction:(UIButton *)sender
{
    [self.lastBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    self.lastBtn.alpha = 0.7;
    self.lastBtn.userInteractionEnabled = YES;
    sender.userInteractionEnabled = NO;
    [sender setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    sender.alpha = 1;
    self.lastBtn = sender;
    NSInteger tags = sender.tag;
    NSString *title = self.titleArray[tags - 200];
    [self pushWithTitle:title];
    
    CGFloat x = sender.frame.origin.x;
    [UIView animateWithDuration:0.3 animations:^{
        if (self.scrollView.contentSize.width - x >= self.scrollView.frame.size.width) {
             self.scrollView.contentOffset = CGPointMake(x - 20, 0);
        } else {
            self.scrollView.contentOffset = CGPointMake(self.scrollView.contentSize.width - self.scrollView.frame.size.width, 0);
        }
       
    }];
}

// 根据名称跳转到对应的控制器
- (void)pushWithTitle:(NSString *)title
{
    if ([title isEqualToString:@"推荐"]) {
        self.recommendVC = [[KLSGKindRecommendViewController alloc] init];
        [self addChildViewController:self.recommendVC];
        self.recommendVC.tname = @"推荐";
        self.recommendVC.Id = self.Id;
        self.recommendVC.view.frame = CGRectMake(0, CGRectGetMaxY(self.scrollView.frame), kScreenWidth, kScreenHeight);
        [self.view addSubview:self.recommendVC.view];
    } else {
        self.childVC = [[KLSGKindChildViewController alloc] init];
        self.childVC.hidesBottomBarWhenPushed = YES;
        self.childVC.tname = title;
        self.childVC.Id = self.Id;
        [self addChildViewController:self.childVC];
        self.childVC.view.frame = CGRectMake(0, CGRectGetMaxY(self.scrollView.frame), kScreenWidth, kScreenHeight);
        [self.view addSubview:self.childVC.view];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
